package com.firstresponder.activity;

import com.firstresponder.util.MessageSender;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;

public class FirstResponderPrefs extends PreferenceActivity implements
		OnSharedPreferenceChangeListener {

	private SharedPreferences prefs;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i("FirstRepsonderPreferences", "On create() called");
		addPreferencesFromResource(R.xml.prefs);
	}

	@Override
	protected void onResume() {
		super.onResume();
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		prefs.registerOnSharedPreferenceChangeListener(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		prefs.unregisterOnSharedPreferenceChangeListener(this);
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		Log.i("Preference Activity", "THIS IS BEING CALLED");
		String number = sharedPreferences.getString(key, "");
		if (number.matches("^\\d{10}$")) {
			Log.i("PreferenceActivity", "number matches sequence");
			MessageSender sender = MessageSender.getInstance();
			sender.setSmsNumber(number);
		} else {
			Log.i("PreferenceActivity", "number does not match sequence");
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Not Valid Number, Please Re-Enter Number")
					.setCancelable(false)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
		}
	}

}
